package org.yak.common.web;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.yak.core.web.Result;
import org.yak.core.web.Result.Status;

import com.alibaba.fastjson.JSONObject;

/**
 *
 * @平台：blunka统一开发平台
 * @文件名称：AjaxFilter.java
 * @文件描述：Ajax请求过滤器，验证用户请求超时提示
 * @author xuqiang
 * @日期：2017年4月17日下午1:31:03
 *
 */
public class AjaxFilter implements Filter{

	private static final Logger logger = Logger.getLogger(AjaxFilter.class);
	//是否ajax请求标记
	private static final String AJAX_REQUEST_FLAG="XMLHttpRequest";

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest servletRequestt, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		 HttpServletRequest request=(HttpServletRequest) servletRequestt;
		 HttpServletResponse response=(HttpServletResponse) servletResponse;

		 HttpServletRequest httpRequest = (HttpServletRequest) request;
		 HttpServletResponse httpResponse = (HttpServletResponse) response;
		 String path = httpRequest.getContextPath();
		 //Principal principal = httpRequest.getUserPrincipal();
		 //String ajaxSubmit = if(ShiroFilter.isAjaxRequest(httpRequest)){
		 if(AjaxFilter.isAjaxRequest(httpRequest)){
			 if (request.getSession(false) == null) {
	    		logger.error("Ajax请求方式，用户回话超时，系统返回登陆超时的json数据");
	    		httpResponse.setCharacterEncoding("UTF-8");
	    		Result rs = new Result();
	    		rs.setStatus(Status.SESSION_TIMEOUT);
	    		rs.setMessage("用户回话超时，请重新登陆");
	    		httpResponse.getWriter().print(JSONObject.toJSON(rs).toString());
	    		httpResponse.getWriter().flush();
	    		httpResponse.getWriter().close();
				 return;
			 }
		 }
		 chain.doFilter(servletRequestt, servletResponse);
	}

	public void destroy() {

	}

	  /**
	   * 判断当前请求是否为ajax请求，默认返回false
	   * @param request
	   * @return
	   * @throws Exception
	   */
	  private static boolean isAjaxRequest(HttpServletRequest request){
		  String ajaxHeader = request.getHeader("X-Requested-With");

		  //如果ajaxHeader被篡改或者不存在则可以通过使用户传入固定参数的方式来判断
		  String ajaxFlag = null == request.getParameter("ajax") ?  "false": request.getParameter("ajax") ;
		  if(AJAX_REQUEST_FLAG.equals(ajaxHeader) || ajaxFlag.equalsIgnoreCase("true")){
			  return true;
		  }

		  return false;
	  }
}
